import time

from PyQt5.QtCore import QThread, QMutex, pyqtSignal


class WorkThread(QThread):
    """
    Thread class, it creates a thread and offer ways to control threads.
        Attributes:
            freq: Timing interval between 2 invokes
            isexit: Stop the thread or just make it in waiting status
    """
    _signal_updateUI = pyqtSignal()

    def __init__(self, parent=None, freq=0.1):
        super(WorkThread, self).__init__(parent)
        self.qmut = QMutex()
        self.isexit = False
        self.freq = freq

    def run(self):
        while True:
            self.qmut.lock()
            if self.isexit:
                break
            self.qmut.unlock()

            self._signal_updateUI.emit()
            time.sleep(self.freq)
        self.qmut.unlock()

    def stop(self):
        # 改变线程状态与终止
        self.qmut.lock()
        self.isexit = True
        self.qmut.unlock()
        self.wait()

    @property
    def signal_updateUI(self):
        return self._signal_updateUI
